package com.pkk.penguin.frame.know.boot.config.handle.zhiyi.synch;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pkk.penguin.frame.know.boot.apis.zhiyi.SynchApi;
import com.pkk.penguin.frame.know.boot.bo.hbsl.MessageType;
import com.pkk.penguin.frame.know.boot.config.common.handle.AbstractWebSocketServer.WebScoketUtil;
import com.pkk.penguin.frame.know.boot.utils.ExecUtil;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @description: 之易同步容器
 * @author: peikunkun
 * @create: 2020-05-20 17:22
 **/
@Slf4j
@Component
public class ZySynchContent {


  /**
   * 之易同步配置
   */
  private static JSONObject zySynchConfig = null;

  /**
   * 之易同步配置文件
   */
  private static String ZHIYI_SYNCH_CONFIG;

  //配置就覆盖默认的
  @Value("${com.pkk.config.zhiyi.synch.authpath}")
  public void setZhiyiSynchConfig(String configPath) {
    ZHIYI_SYNCH_CONFIG = configPath;
    if (StringUtils.isBlank(ZHIYI_SYNCH_CONFIG)) {
      throw new IllegalStateException("请指定之易同步配置文件");
    }
    handleSupportPlatform();
  }

  /**
   * 用户鉴权信息
   */
  public static ConcurrentHashMap<String, ConcurrentHashMap<String, SynchApi>> USER_AUTH_INFO = new ConcurrentHashMap<>();
  /**
   * 授权平台
   */
  public static LinkedHashSet<String> AUTH_PLATEFORM_SET = new LinkedHashSet<>();

  /**
   * 授权用户
   */
  public static LinkedHashSet<String> AUTH_USER_SET = new LinkedHashSet<>();


  /**
   * @Description: 处理支持的平台
   * @return: void
   * @Author: peikunkun
   * @Date: 2020/6/1 0001 上午 11:56
   */
  private void handleSupportPlatform() {
    zySynchConfig = ExecUtil.readJsonFile(ZHIYI_SYNCH_CONFIG);
    if (null != zySynchConfig) {
      log.info("【读取之易同步数据配置】-[{}]", zySynchConfig);
      //认证后台信息
      final JSONArray zyadmin = zySynchConfig.getJSONArray("zyadmin");
      for (int i = 0; i < zyadmin.size(); i++) {
        final JSONObject admin = zyadmin.getJSONObject(i);

        //一个平台简称
        final Set<String> platformKey = admin.keySet();
        platformKey.stream().forEach(p -> {
          AUTH_PLATEFORM_SET.add(p);
        });
      }
    }

  }

  @Resource
  private ZySynchWebSocketServer zySynchWebSocketServer;

  /**
   * @Description: 处理之易认证
   * @return: void
   * @Author: peikunkun
   * @Date: 2020/5/26 0026 上午 10:03
   */
  public void handleZhiYiAuth(String uname, String pwd) {
    /**
     * 读取之易同步配置文件
     */
    zySynchConfig = ExecUtil.readJsonFile(ZHIYI_SYNCH_CONFIG);
    if (null == zySynchConfig) {
      log.warn("未配置任何平台");
      return;
    }
    log.info("【读取之易同步数据配置】-[{}]", zySynchConfig);
    //认证后台信息
    final JSONArray zyadmin = zySynchConfig.getJSONArray("zyadmin");

    if (StringUtils.isBlank(uname) || StringUtils.isBlank(pwd)) {
      log.warn("【读取之易同步数据配置】-未获取到授权账号信息-[{}]", zySynchConfig);
    } else {
      StringBuffer sb = new StringBuffer();

      //鉴权信息
      ConcurrentHashMap<String, SynchApi> authInfo = new ConcurrentHashMap<>();
      AtomicBoolean authUser = new AtomicBoolean(false);
      for (int i = 0; i < zyadmin.size(); i++) {
        final JSONObject admin = zyadmin.getJSONObject(i);

        //一个平台简称
        final Set<String> platformKey = admin.keySet();
        platformKey.stream().forEach(p -> {
          final String adminUrl = admin.getString(p);
          try {
            authInfo.put(p, new SynchApi(adminUrl, uname, pwd).login());
            authUser.set(true);
          } catch (Exception e) {
            sb.append("平台:" + p).append("-[登录异常]:").append(e.getMessage()).append("\n");
          }
          log.info("【之易数据同步服务用户授权操作】-[{}]-[{}]", p, uname);
        });
      }
      USER_AUTH_INFO.put(uname, authInfo);
      if (authUser.get()) {
        AUTH_USER_SET.add(uname);
      }
      final String logStr = sb.toString();
      if (StringUtils.isNotBlank(logStr)) {
        WebScoketUtil.broadcost(zySynchWebSocketServer.getWebSocket(), MessageType.ONLINE, logStr);
      } else {
        WebScoketUtil.broadcost(zySynchWebSocketServer.getWebSocket(), MessageType.ONLINE, "用户鉴权成功");
      }


    }
  }


}
